using System;
using System.Net;
using System.Net.NetworkInformation;

namespace PingInfo.avalonia.Helpers
{
    public class PingHelper
    {
        private readonly Ping _ping;
        public PingReply LastReply { get; private set; }

        public class PingReply
        {
            public long RoundTripTime { get; set; }
            public byte Ttl { get; set; }
            public bool Success { get; set; }
        }

        public PingHelper()
        {
            _ping = new Ping();
        }

        public bool SendPing(IPAddress address, int timeout, int bufferSize)
        {
            try
            {
                byte[] buffer = new byte[bufferSize];
                new Random().NextBytes(buffer);

                var reply = _ping.Send(address, timeout, buffer);

                if (reply.Status != IPStatus.Success)
                {
                    LastReply = new PingReply { Success = false };
                    return false;
                }

                LastReply = new PingReply
                {
                    RoundTripTime = reply.RoundtripTime,
                    Ttl = (byte)(reply.Options?.Ttl ?? 0),
                    Success = true
                };

                return true;
            }
            catch (PingException)
            {
                LastReply = new PingReply { Success = false };
                return false;
            }
        }

        public void Dispose()
        {
            _ping?.Dispose();
        }
    }
}